package com.azxc.rapid.auth.config;

import com.azxc.rapid.auth.jianguan.SuperviseAuthenticationProvider;
import com.azxc.rapid.auth.sso.SsoAuthenticationProvider;
import com.azxc.rapid.supervise.feign.ISuperviseClient;
import com.azxc.rapid.system.user.feign.IUserClient;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import com.azxc.rapid.auth.support.RapidPasswordEncoderFactories;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Arrays;

/**
 * Security配置
 *
 *
 */
@Configuration
@AllArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	private ISuperviseClient superviseClient;

	private UserDetailsService userDetailsService;

	private IUserClient userClient;

	@Bean
	@Override
	@SneakyThrows
	public AuthenticationManager authenticationManagerBean() {
		return super.authenticationManagerBean();
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return RapidPasswordEncoderFactories.createDelegatingPasswordEncoder();
	}

	@Override
	@SneakyThrows
	protected void configure(HttpSecurity http) {
		http.httpBasic().and().csrf().disable();
	}
	protected AuthenticationManager authenticationManager()  {
		//密码登录provide
		DaoAuthenticationProvider daoAuthenticationProvider=new DaoAuthenticationProvider();
		daoAuthenticationProvider.setUserDetailsService(userDetailsService);
		daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
		//额外增加综合监管的provide
		ProviderManager authenticationManager = new ProviderManager(Arrays.asList(daoAuthenticationProvider
			,superviseCodeAuthenticationProvider()/*,ssoAuthenticationProvider()*/));
		 //不擦除认证密码，擦除会导致TokenBasedRememberMeServices因为找不到Credentials再调用UserDetailsService而抛出UsernameNotFoundException
		 //authenticationManager.setEraseCredentialsAfterAuthentication(false);
		 return authenticationManager;

	}

	@Bean
	public SuperviseAuthenticationProvider superviseCodeAuthenticationProvider() {
		return new SuperviseAuthenticationProvider(superviseClient);
	}

	@Bean
	public SsoAuthenticationProvider ssoAuthenticationProvider(){
		return new SsoAuthenticationProvider(userClient);
	}
}
